<template>
  <div class="code-gen-container page-container">
    <fyh-form :module-path="modelPath" v-model="formState">
      <template #operation>
        <el-button type="primary" @click="generateCode">生成代码</el-button>
        <el-button @click="resetForm">重置</el-button>
        <el-button @click="previewCode">预览</el-button>
      </template>
    </fyh-form>

    <div class="mb20">
      <div class="table-header">
        <span>字段信息</span>
        <el-button type="primary" size="small" @click="addField">添加字段</el-button>
      </div>
      <fyh-table
        :data="formState.fields"
        :module-path="modelPath"
        files-name="default"
      >
        <template #operation="{ row }">
          <el-button type="danger" link @click="removeField(row)">删除</el-button>
        </template>
      </fyh-table>
    </div>

    <the-dialog
      v-model:visible="dialogVisible"
      :title="dialogTitle"
      width="60%"
      :show-btns="false"
    >
      <pre>{{ previewContent }}</pre>
    </the-dialog>
  </div>
</template>

<script setup lang='ts' name="code-gen">
import { ElMessage } from 'element-plus'
import FyhForm from "@/components/FyhComs/FyhForm.vue";
import FyhTable from "@/components/FyhComs/FyhTable.vue";
import TheDialog from "@/components/Dialog/index.vue";
import { generateCode as generateCodeApi, previewCode as previewCodeApi } from "./api";

const modelPath = `views/system/systemTool/codeGen`;

// 表单状态
const formState = reactive({
  moduleName: '',
  packageName: '',
  author: '',
  genType: 1,
  fields: [
    {
      fieldName: '',
      fieldComment: '',
      physicalType: 'string',
      dataType: 'string',
      fieldProp: '',
      insert: true,
      edit: true,
      list: true,
      query: true,
      queryType: 'LIKE',
      required: false,
      htmlType: 'input',
      dictType: ''
    }
  ]
})

// 对话框状态
const dialogVisible = ref(false);
const dialogTitle = ref('');
const previewContent = ref('');

// 添加字段
const addField = () => {
  formState.fields.push({
    fieldName: '',
    fieldComment: '',
    physicalType: 'string',
    dataType: 'string',
    fieldProp: '',
    insert: true,
    edit: true,
    list: true,
    query: true,
    queryType: 'LIKE',
    required: false,
    htmlType: 'input',
    dictType: ''
  })
}

// 删除字段
const removeField = (row: any) => {
  if (formState.fields.length <= 1) {
    ElMessage.warning('至少保留一个字段')
    return
  }
  const index = formState.fields.findIndex(field => field === row);
  if (index > -1) {
    formState.fields.splice(index, 1);
  }
}

// 重置表单
const resetForm = () => {
  formState.moduleName = ''
  formState.packageName = ''
  formState.author = ''
  formState.genType = 1
  formState.fields = [
    {
      fieldName: '',
      fieldComment: '',
      physicalType: 'string',
      dataType: 'string',
      fieldProp: '',
      insert: true,
      edit: true,
      list: true,
      query: true,
      queryType: 'LIKE',
      required: false,
      htmlType: 'input',
      dictType: ''
    }
  ]
}

// 处理表单数据，将其转换为接口需要的格式
const processFormData = () => {
  // 验证必填字段
  if (!formState.moduleName) {
    throw new Error('模块名不能为空');
  }
  
  // 构造接口需要的数据结构
  const requestData = {
    moduleName: formState.moduleName,
    packageName: formState.packageName,
    author: formState.author,
    genType: formState.genType,
    fields: formState.fields.map(field => ({
      fieldName: field.fieldName,
      fieldComment: field.fieldComment,
      physicalType: field.physicalType,
      dataType: field.dataType,
      fieldProp: field.fieldProp,
      insert: field.insert,
      edit: field.edit,
      list: field.list,
      query: field.query,
      queryType: field.queryType,
      required: field.required,
      htmlType: field.htmlType,
      dictType: field.dictType
    }))
  };
  
  return requestData;
}

// 生成代码
const generateCode = async () => {
  try {
    // 处理表单数据
    const requestData = processFormData();
    
    // 调用后端 API 生成代码
    await generateCodeApi(requestData);
    ElMessage.success('代码生成成功');
  } catch (error) {
    if (error instanceof Error) {
      ElMessage.error(error.message);
    } else {
      ElMessage.error('代码生成失败');
    }
  }
}

// 预览代码
const previewCode = async () => {
  try {
    dialogTitle.value = '代码预览';
    previewContent.value = '正在生成预览...';
    dialogVisible.value = true;
    
    // 处理表单数据
    const requestData = processFormData();
    
    // 调用后端 API 获取预览内容
    const res = await previewCodeApi(requestData);
    previewContent.value = JSON.stringify(res, null, 2);
  } catch (error) {
    if (error instanceof Error) {
      previewContent.value = '预览生成失败: ' + error.message;
    } else {
      previewContent.value = '预览生成失败';
    }
  }
}
</script>

<style scoped>
.code-gen-container {
  padding: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.mb20 {
  margin-bottom: 20px;
}
</style>